﻿//<my-matriculator - a simple tool for registering racers in a USAC cyclocross race>
//Copyright (C) <2011>  <Steven Rivers>

//This program is free software: you can redistribute it and/or modify
//it under the terms of the GNU General Public License as published by
//the Free Software Foundation, either version 3 of the License, or
//(at your option) any later version.

//This program is distributed in the hope that it will be useful,
//but WITHOUT ANY WARRANTY; without even the implied warranty of
//MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//GNU General Public License for more details.

//You should have received a copy of the GNU General Public License
//along with this program.  If not, see <http://www.gnu.org/licenses/>.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Controls;
using Registration.Model;
using Registration.Model.Entities;


namespace Registration
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow
    {
        public UsacRider MyRacer
        {
            get;
            private set;
        }

        public IList<UsacRider> MyMatchedRiders
        {
            get;
            private set;
        }

        public MainWindow()
        {
            InitializeComponent();
            ClearRacer();
            RefreshListView();
            cmbField.ItemsSource = FieldsDb.GetOpenCategories();

            txtRaceName.Text = "Race: " + Config.GetRaceName();
            txtRaceDate.Text = "Date: " + Config.GetRaceDate();

            var myBrush = new ImageBrush {ImageSource = new BitmapImage(new Uri("./background.jpg", UriKind.Relative))};

            Background = myBrush;
            Opacity = .98;

            if(Config.IsReadOnly())
            {
                txtLicenseNumber.IsReadOnly = true;
                txtFirstName.IsReadOnly = true;
                txtLastName.IsReadOnly = true;
                txtGender.IsReadOnly = true;
                txtClubName.IsReadOnly = true;
                cmbField.IsEnabled = false;
                btnRegisterRider.IsEnabled = false;
                txtLicenseNumber.Text = "READ ONLY MODE !!!!!";
            }
             
        }

        private int GetLicenseAsInt()
        {
            int licNum;
            Int32.TryParse(txtLicenseNumber.Text, out licNum);
            return licNum;
        }

        private void GetRider()
        {
            int licNum = GetLicenseAsInt();
            MyRacer = UsacDb.GetRacer(licNum);
            gridRiderDetails.DataContext = MyRacer;
        }

        private string ErrorMessage { get; set; }

        private void ValidateAll()
        {
            ErrorMessage = String.Empty;
            var requestErrors = new List<string>();

            if(String.IsNullOrEmpty(txtLicenseNumber.Text))
                requestErrors.Add("License number must not be blank");
            if(String.IsNullOrEmpty(txtLastName.Text))
                requestErrors.Add("Last name must not be blank");
            if(String.IsNullOrEmpty(txtFirstName.Text))
                requestErrors.Add("First name  must not be blank");
            var cat = (Category)cmbField.SelectedItem;
            if (cat == null)
            {
                requestErrors.Add("Category must not be blank");
            }
            ErrorMessage = string.Join("; ", requestErrors);
        }

        private void ClickRegisterRider(object sender, RoutedEventArgs e)
        {
            ValidateAll();

            if (!string.IsNullOrEmpty(ErrorMessage))
            {
                MessageBox.Show(ErrorMessage);
                return;
            }

            if (MyRacer == null)
            {
                MyRacer = new UsacRider(GetLicenseAsInt(),
                    txtLastName.Text, txtFirstName.Text, "", "", txtGender.Text, txtGender.Text, "12/31/2011", txtClubName.Text, txtClubName.Text, txtClubName.Text, "999");
            }

            var cat = (Category)cmbField.SelectedItem;
            var f = FieldsDb.GetFieldUpdateBib(cat.CategoryField);

            if (EntryDb.FindEntryByBib(f.NextBib, f.FieldId) == null)
            {
                var entry = new Entry(-1, f.NextBib, MyRacer.License, cat.CategoryId, cat.CategoryName, MyRacer.FirstName, MyRacer.LastName, MyRacer.Club, MyRacer.Gender, MyRacer.RacingAge);
                EntryDb.AddEntry(entry);
            }
            else
            {
                MessageBox.Show("Duplicate bib!!!");
            }
            ClearRacer();
        }

        private void ClearRacer(bool bclearLicense=true, bool refeshGrid=true)
        {
            MyRacer = null;
            gridRiderDetails.DataContext = MyRacer;
            cmbField.Text = "";
            txtBib.Text = "";
            if (bclearLicense) txtLicenseNumber.Text = "";
            txtClubName.Text =  "";
            txtFirstName.Text = "";
            txtLastName.Text = "";
            txtRacingAge.Text = "";
            txtGender.Text = "";
            if (refeshGrid) RefreshListView();
        }


        private void RefreshListView()
        {
            IList<Entry> entries; 
            if (!String.IsNullOrEmpty(txtSearchCriteria.Text))
            {
                entries = EntryDb.FindRider(txtSearchCriteria.Text);
                listEntries.Foreground = Brushes.Red;
                listEntries.FontStyle = FontStyles.Italic;
            }
            else
            {
                entries = EntryDb.GetAllEntries().ToList();
                listEntries.Foreground = Brushes.Black;
                listEntries.FontStyle = FontStyles.Normal;
            }

            listEntries.ItemsSource = entries;
            txtTotalRiders.Text = "Total Riders:  " + entries.Count;
            txtUniqueRiders.Text = "Unique Riders: " + (from e in entries select e.License ).Distinct().Count();
            txtOneDays.Text = "One Day + Anual:  " + entries.Count(e => e.License <= 0 );
        }

        private void OnDeleteEntry(object sender, RoutedEventArgs e)
        {
            if (Config.IsReadOnly()) return;

            if ( listEntries.SelectedItems.Count == 1 )
            {
                var entry = (Entry)listEntries.SelectedItems[0];

                if (MessageBoxResult.Yes == MessageBox.Show("Are you sure you want to delete entry??", "Confirm Delete Entry", MessageBoxButton.YesNo))
                {
                    EntryDb.DeleteEntry(entry);
                    RefreshListView();
                }
            }
        }

        private void OnComboChanged(object sender, EventArgs e)
        {
            var s = cmbField.Text;
            Category cat = FieldsDb.FindCategory(s);
            if (cat == null) return;
            int bib = FieldsDb.PreviewNextBib(cat.CategoryId);
            txtBib.Text = bib.ToString();
        }

        private void OnClickResults(object sender, RoutedEventArgs e)
        {
            if (Config.IsReadOnly()) return;
            var window = new ResultsWindow();
            window.Show();
        }

        private void OnClickStartList(object sender, RoutedEventArgs e)
        {
            if (Config.IsReadOnly()) return;
            var window = new StartList();
            window.Show();
        }

        private void OnClickTools(object sender, RoutedEventArgs e)
        {
            if (Config.IsReadOnly()) return;

            var window = new Tools();
            window.ShowDialog();
            listEntries.Items.Refresh();
        }

        private void OnLicenseKeyUp(object sender, KeyEventArgs e)
        {
            if (e.Key != Key.Enter) return;
            if (e.Key == Key.Down || e.Key == Key.Up)
            {
                e.Handled = true;
                return;
            }
            GetSelectedRider();
            LicensePopup.IsOpen = false;
        }

        private void OnKillFocus(object sender, KeyboardFocusChangedEventArgs e)
        {
            if (!LicensePopup.IsOpen)
                GetRider();

        }

        private void OnEditEntry(object sender, RoutedEventArgs e)
        {
            if (Config.IsReadOnly()) return;

            if (listEntries.SelectedItems.Count != 1) return;
            var window = new EditEntry((Entry)listEntries.SelectedItem);
            window.ShowDialog();
            RefreshListView();
        }

        private void OnSearchKeyUp(object sender, KeyEventArgs e)
        {
            RefreshListView();
        }

        private void OnClickFields(object sender, RoutedEventArgs e)
        {
            if (Config.IsReadOnly()) return;
            var window = new FieldsSetup();
            window.ShowDialog();
            cmbField.ItemsSource = FieldsDb.GetOpenCategories();
        }

        private void OnMatchesLicenseMouseDown(object sender, MouseButtonEventArgs e)
        {
            GetSelectedRider();

            if (e != null)
                e.Handled = true;
        }

        private void GetSelectedRider()
        {
            var selected = (UsacRider)listAllRiders.SelectedItem;
            if (selected == null) return;
            MyRacer = selected;
            gridRiderDetails.DataContext = MyRacer;
            txtLicenseNumber.Text = MyRacer.License.ToString();
            LicensePopup.IsOpen = false;
        }

        private void OnPreviewLicenseKeyDown(object sender, KeyEventArgs e)
        {
            if (!LicensePopup.IsOpen) return;
            var index = listAllRiders.SelectedIndex;
            switch (e.Key)
            {
                case Key.Down:
                    index++;
                    break;
                case Key.Up:
                    if (index == -1)
                    {
                        index = listAllRiders.Items.Count - 1;
                    }
                    else
                    {
                        --index;
                    }
                    break;
            }

            if (index == listAllRiders.SelectedIndex) return;
            if (index < 0 || index > listAllRiders.Items.Count - 1)
            {
                listAllRiders.SelectedIndex = -1;
            }
            else
            {
                listAllRiders.SelectedIndex = index;
                listAllRiders.ScrollIntoView(listAllRiders.SelectedItem);
            }
            e.Handled = true;
        }

        private void OnLicenseTextChanged(object sender, TextChangedEventArgs e)
        {
            if (String.IsNullOrEmpty(txtLicenseNumber.Text))
            {
                LicensePopup.IsOpen = false;
            }
            else
            {
                MyMatchedRiders = UsacDb.FindByLicense(txtLicenseNumber.Text);
                listAllRiders.ItemsSource = MyMatchedRiders;
                if (MyMatchedRiders.Count > 0)
                {
                    LicensePopup.IsOpen = true;
                    listAllRiders.Items.Refresh();
                    listAllRiders.SelectedIndex = 0;
                }
                else
                    LicensePopup.IsOpen = false;
            }
        }
    }
}
